package com.ymttest.business.service.YMTTrading;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONObject;

import com.google.common.collect.Lists;
import com.ymatou.iapi.delivery.parameter.DeliverGoodsReq;
import com.ymatou.iapi.delivery.parameter.DeliveryInfo;
import com.ymatou.iapi.delivery.parameter.ModifyOrSupplementBillNoInfo;
import com.ymatou.iapi.delivery.parameter.ModifyOrSupplementBillNoReq;
import com.ymatou.iapi.delivery.service.DeliverGoodsCall;
import com.ymatou.iapi.delivery.service.ModifyOrSupplementBillNoCall;
import com.ymatou.iapi.leaf.parameter.GetSeqReq;
import com.ymatou.iapi.leaf.service.GetSeqIdsCall;
import com.ymatou.iapi.optrade.parameter.enums.AppTerminalSourceEnum;
import com.ymatou.iapi.optrade.parameter.enums.CancelOrderTypeEnum;
import com.ymatou.iapi.optrade.parameter.enums.LogisticsTypeEnum;
import com.ymatou.iapi.optrade.parameter.enums.OrderSourceEnum;
import com.ymatou.iapi.optrade.parameter.enums.ProductRefundChannelEnum;
import com.ymatou.iapi.optrade.parameter.enums.SalesTypeEnum;
import com.ymatou.iapi.optrade.parameter.enums.TerminalSourceEnum;
import com.ymatou.iapi.optrade.parameter.req.AcceptOrderReq;
import com.ymatou.iapi.optrade.parameter.req.AuthenticateCenterNotifyReq;
import com.ymatou.iapi.optrade.parameter.req.AuthenticateDeliveryReq;
import com.ymatou.iapi.optrade.parameter.req.CancelOrderReq;
import com.ymatou.iapi.optrade.parameter.req.ConfirmReceiveReq;
import com.ymatou.iapi.optrade.parameter.req.MarkOrderLockReq;
import com.ymatou.iapi.optrade.parameter.req.PayReq;
import com.ymatou.iapi.optrade.parameter.req.PlaceOrderReq;
import com.ymatou.iapi.optrade.parameter.req.SyncSignedOrderReq;
import com.ymatou.iapi.optrade.parameter.utill.Utils;
import com.ymatou.iapi.optrade.parameter.vo.ActivityVo;
import com.ymatou.iapi.optrade.parameter.vo.BizVo;
import com.ymatou.iapi.optrade.parameter.vo.IdentifyProdArrivedVo;
import com.ymatou.iapi.optrade.parameter.vo.OrderGroupVo;
import com.ymatou.iapi.optrade.parameter.vo.OrderItemVo;
import com.ymatou.iapi.optrade.parameter.vo.OrderVo;
import com.ymatou.iapi.optrade.parameter.vo.SyncSignedOrderBizParamVo;
import com.ymatou.iapi.optrade.resp.Order;
import com.ymatou.iapi.optrade.resp.TradingServiceResp;
import com.ymatou.iapi.optrade.service.AuthenticateCenterNotifyCall;
import com.ymatou.iapi.optrade.service.AuthenticateDeliveryCall;
import com.ymatou.iapi.optrade.service.CancelOrderCall;
import com.ymatou.iapi.optrade.service.ConfirmReceiveCall;
import com.ymatou.iapi.optrade.service.MarkOrderLockCall;
import com.ymatou.iapi.optrade.service.PayReqCall;
import com.ymatou.iapi.optrade.service.PlaceOrderCall;

import com.ymatou.iapi.optrade.service.RefundService;
import com.ymatou.iapi.optrade.service.SellerAcceptOrderCall;
import com.ymatou.iapi.optrade.service.SyncSignedOrderCall;
import com.ymatou.iapi.payment.parameter.QueryByTradingIdBean;
import com.ymatou.iapi.payment.service.QueryByTradingIdCall;

import com.ymatou.iapi.synctrade.service.TradingSyncService;
import com.ymt.base.YmatouEasyCall;
import com.ymt.core.tool.Logger;
import com.ymttest.business.service.AccountCallServiceV2;

import com.ymttest.business.service.PayGateWayCallService;
import com.ymttest.business.service.ProductManagerCallServiceV2;

import com.ymttest.database.sharding.db.sharding.model.OrderDetailPo;
import com.ymttest.database.sharding.db.sharding.model.OrderPo;
import com.ymttest.database.sharding.db.sqlwapper.OrderShardingWapper;

import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.TestDataManager;

public class TradingCallService {

	private static Long sellerId = Long.valueOf(EnvSetup
			.getData("autotest_seller1"));
	private static String sellerName = String.valueOf(EnvSetup
			.getData("autotest_sellerName1"));

	/**
	 * callPlaceOrderService
	 * 
	 * @param placeorderBean
	 * @return
	 */
	public static TradingServiceResp callPlaceOrderService(
			PlaceOrderReq placeOrderReq) {

		PlaceOrderCall placeorderCall = new PlaceOrderCall();

		TradingServiceResp orderResp = new TradingServiceResp();

		placeorderCall.setData(false, placeOrderReq);

		try {

			if (placeOrderReq.getMainOrderId() % 10000 != placeOrderReq
					.getUserId() % 10000) {

				// 设置主单号
				placeOrderReq.setMainOrderId(genMainOrderId(placeOrderReq
						.getUserId()));
			}

			placeorderCall.callService();

			// 如果下单失败，则重试3次，如果依然失败，则抛出exception
			int n = 0;
			retryPlaceOrder(placeorderCall, n);

			long userId = placeOrderReq.getUserId();

			orderResp.setUserId(userId);

			List<Long> orderIds = placeorderCall.getPlaceOrderResp()
					.getOrderIds();

			List<Order> orderList = new ArrayList<Order>();

			for (int i = 0; i < orderIds.size(); i++) {

				Order order = new Order();

				long orderId = orderIds.get(i);

				OrderShardingWapper orderShardingWapper = new OrderShardingWapper();

				OrderPo orderPo = orderShardingWapper
						.selectOrderbyOrderId(orderId);

				List<OrderDetailPo> orderDetailPoList = orderShardingWapper
						.selectOrderDetailbyOrderId(orderId);

				order.setOrderPo(orderPo);
				order.setOrderDetailPoList(orderDetailPoList);

				orderList.add(order);

			}

			if (placeOrderReq.getBizSource() != null) {

				orderResp.setBizId(placeOrderReq.getBizSource().getBizId());
			}

			orderResp.setOrderList(orderList);

			orderResp.setMainOrderId(placeOrderReq.getMainOrderId());

		} catch (Exception e) {

			e.printStackTrace();

		}

		// 下架由下单创建的商品
		Map<Long, List<String>> map = new HashMap<Long, List<String>>();

		placeOrderReq.getOrderGroups().forEach(
				group -> {

					long sellerId = group.getSellerId();

					List<String> proids = Lists.newArrayList();
					if (null != group.getOrders())
						group.getOrders().forEach(
								order -> order.getOrderItems()
										.forEach(
												item -> proids.add(item
														.getProductId())));

					map.put(sellerId, proids);

				});

		map.forEach((k, v) -> {

			try {

				ProductManagerCallServiceV2.batchSetProductOffSale(v,
						k.intValue());

			} catch (Exception e) {

				e.printStackTrace();

				Logger.info("下架由下单创建的商品出现异常！");
			}
		});

		return orderResp;
	}

	/**
	 * buildStandPlaceOrderReq 一个商家，一个商品，生成一个订单 标准类
	 *
	 * @return
	 */
	public static PlaceOrderReq buildStandPlaceOrderReq() {

		PlaceOrderReq req = new PlaceOrderReq();

		req.setAddressId(772208L);
		req.setRecvMobile("136" + TestDataManager.getRandomNum(8));
		req.setRecvName("testUser");
		req.setAppId("ymt autotest");
		req.setUserId(Long.valueOf(EnvSetup.getData("BuyUserId")));

		req.setAddress("上海 静安 江场三路");
		req.setPostCode("200000");

		req.setEquipmentId(TestDataManager.getRandomUUID().toString());
		req.setDeviceId(TestDataManager.getRandomUUID().toString());
		req.setSourceIp(TestDataManager.getRandomIp());

		req.setAppTerminalSource(AppTerminalSourceEnum.Phone);
		req.setOrderSource(OrderSourceEnum.Wechat);
		req.setTerminalSource(TerminalSourceEnum.Android);

		req.setMainOrderId(genMainOrderId(req.getUserId()));

		req.setPayDeductAmount(null);

		return req;
	}

	/**
	 * 一个商家，一个商品，生成一个订单 demo
	 * 
	 * @param isBargainGroup
	 *            是否砍价团订单 砍价团订单不由交易扣库存
	 * @return
	 */
	public static PlaceOrderReq buildDemoReq(boolean isBargainGroup) {

		PlaceOrderReq req = TradingCallService.buildStandPlaceOrderReq();

		// 订单信息
		OrderVo orderVo = TradingCallService.createOrderVo();

		// 订单商品信息
		List<OrderItemVo> items = new ArrayList<OrderItemVo>();

		if (isBargainGroup) {

			// 设置为砍价团订单,不需要交易扣库存，随意设置商品和规格id
			BizVo biz = new BizVo();

			biz.setBizId(TestDataManager.getRandomNum(9));
			biz.setBizSubType(1);
			biz.setBizType(1);

			req.setBizSource(biz);

			// 创建订单项
			OrderItemVo orderItemVo = createOrderItemVo(TestDataManager
					.getRandomUUID().toString(), TestDataManager
					.getRandomUUID().toString());

			items.add(orderItemVo);
			orderVo.setOrderItems(items);
		} else {

			// 创建一个普通商品
			TradingProductVo product = TradingProductVo.createPro(sellerId,
					sellerName, 100);

			// 创建订单项
			OrderItemVo orderItemVo = createOrderItemVo(product.getProductId(),
					product.getCatalogId());
			items.add(orderItemVo);

			orderVo.setOrderItems(items);
		}

		// 一个商家组
		OrderGroupVo groupVo = TradingCallService.createOrderGroupVo(sellerId,
				sellerName);

		// 添加订单
		groupVo.setOrders(Lists.newArrayList(orderVo));

		req.setOrderGroups(Lists.newArrayList(groupVo));

		return req;
	}

	/**
	 * 创建订单组
	 * 
	 * @param sellerId
	 * @param sellerName
	 * @return OrderGroupVo
	 */
	public static OrderGroupVo createOrderGroupVo(long sellerId,
			String sellerName) {

		OrderGroupVo groupVo = new OrderGroupVo();

		groupVo.withSellerId(sellerId).withSellerName(sellerName);

		return groupVo;
	}

	/**
	 * 创建订单项
	 * 
	 * @return
	 */
	public static OrderVo createOrderVo() {

		OrderVo orderVo = new OrderVo();

		orderVo.withLogisticsType(LogisticsTypeEnum.OVERSEAS_DELIVERY)
				.withAutoCancelOrderHours(BigDecimal.ONE)
				.withLeaveWord("尽快发货！").withLogisticsAging(10);

		return orderVo;
	}

	/**
	 * createOrderItemVo
	 * 
	 * @param productId
	 * @return OrderItemVo
	 */
	public static OrderItemVo createOrderItemVo(String productId,
			String catalogId) {

		OrderItemVo orderItem = new OrderItemVo();

		BigDecimal price = new BigDecimal(new Random().nextInt(50) + 30);
		// BigDecimal price = new BigDecimal("1000");
		BigDecimal freight = new BigDecimal(new Random().nextInt(20) + 10);

		orderItem.setProductPrice(price);
		orderItem.setOriginalPrice(price);

		orderItem.setFreight(freight);
		orderItem.setProductNum(new Random().nextInt(4) + 2);
		orderItem.setProductId(productId);
		orderItem.setCatalogId(catalogId);

		orderItem.setSalesType(SalesTypeEnum.AlreadyInStock);
		orderItem.setFirstCategoryId(1001);
		orderItem.setSecondCategoryId(1002);
		orderItem.setThirdCategoryId(1003);
		orderItem.setPreSale(false);
		orderItem.setProductRefundChannel(ProductRefundChannelEnum.None);
		orderItem
				.setPictureUrl("http://pic1.ymatou.com/G01/shangou/M00/39/85/rBBlD1k-U5eAMqEfAAIULSyYXWM521_104_78_n_w_o.jpg");
		orderItem.setSku("sku111");
		orderItem.setProperty("属性");
		orderItem.setBrandId(1234);
		orderItem.setProductName("自动化测试商品+" + TestDataManager.getRandomNum(10));
		orderItem.setProductRecordNo("9876");

		return orderItem;
	}

	/**
	 * createActivityVo
	 * 
	 * @param activityId
	 * @return
	 */
	public static ActivityVo createActivityVo(long activityId) {

		ActivityVo activityVo = new ActivityVo();

		activityVo.setActivityId(activityId);
		activityVo.setActivityTemplateId(12345678);
		// activityVo.setProductInActivityId(4);

		return activityVo;
	}

	/**
	 * 根據userid 生成主单号
	 * 
	 * @param userId
	 * @return
	 */
	public static Long genMainOrderId(long userId) {

		long last4 = userId % 10000;

		GetSeqReq req = new GetSeqReq();
		GetSeqIdsCall call = new GetSeqIdsCall();

		long nativeId = 0L;

		req.setCount(1);
		req.setSeqName(String.format("main_%s", last4));

		call.setData(false, req);

		try {
			call.callService();

		} catch (Exception e) {

			e.printStackTrace();
		}

		nativeId = call.getids().get(0);

		nativeId += 100000;

		return nativeId * 10000 + last4;

	}

	public static void retryPlaceOrder(PlaceOrderCall placeorderCall, int n) {

		try {

			if (n != 3 && placeorderCall.getCode() == 500) {

				placeorderCall.callService();
				n = n + 1;

				retryPlaceOrder(placeorderCall, n);
			} else if (n == 3)
				throw new Exception("下单失败，终止下单");

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @param userId
	 *            用户id
	 * @param earnestAmount
	 *            定金金额
	 * @param tradingId
	 *            交易号
	 */
	public static Long payEngageOrder(long userId, BigDecimal earnestAmount,
			long tradingId) {

		// 支付定金
		return TradingCallService.payOrder(userId, earnestAmount, tradingId, 2);
	}

	/**
	 * 二次确认并支付
	 * 
	 * @param userId
	 *            用户id
	 * @param orderId
	 *            订单id
	 */
	public static Long payFullPaidOrder(long userId, long orderId) {

		List<Long> bookingConfirmOrderIds = new ArrayList<Long>();
		bookingConfirmOrderIds.add(orderId);

		TradingServiceResp fullPaidResp = TradingPlaceEngageOrderCallService
				.placeOrderWithBookingConfirmOrderIds(bookingConfirmOrderIds);
		BigDecimal useAccountAmount = fullPaidResp.getPayableAmount();
		long fullPaidTradingId = fullPaidResp.getTradingId();

		// 二次确认并支付
		return TradingCallService.payOrder(userId, useAccountAmount,
				fullPaidTradingId, 1);
	}

	/**
	 * 取消订单
	 * 
	 * @param orderId
	 * @param type
	 * @param userId
	 */
	public static void cancelOrder(long orderId, CancelOrderTypeEnum type,
			long userId) {

		CancelOrderReq cancelorderReq = new CancelOrderReq();
		CancelOrderCall cancelordercall = new CancelOrderCall();

		cancelorderReq.setCancelReason("自动化测试取消订单");
		cancelorderReq.setCancelType(type);
		cancelorderReq.setOrderId(orderId);
		cancelorderReq.setUserId(userId);

		cancelordercall.setData(false, cancelorderReq);
		try {

			cancelordercall.callService();

		} catch (Exception e) {
			Logger.info(String.format("########取消订单:%s 异常", orderId));
		}
	}

	/**
	 * 支付前取消订单
	 * 
	 * @param CancelOrderTypeEnum
	 *            type
	 * @return
	 */
	public static TradingServiceResp cancelOrderBeforePaid(
			CancelOrderTypeEnum buyercancelorder) {

		TradingServiceResp placeOrderResp = TradingPlaceOrderCallService
				.placeOrderWithTwoProcutInOneOrder(false, false);

		long userId = placeOrderResp.getUserId();

		OrderPo orderPo = placeOrderResp.getOrderList().get(0).getOrderPo();

		long orderId = orderPo.getOrderId();

		long sellerId = orderPo.getSellerId();

		long operateId;

		switch (buyercancelorder.getCode()) {
		case 1:
			operateId = userId;
			break;
		case 2:
			operateId = sellerId;
			break;
		case 4:
			operateId = -1;
			break;
		default:
			operateId = -1;
			break;

		}

		cancelOrder(orderId, buyercancelorder, operateId);

		return placeOrderResp;

	}

	/**
	 * 支付后取消订单
	 * 
	 * @param CancelOrderTypeEnum
	 *            type
	 * @return
	 */
	public static TradingServiceResp cancelOrderAfterPaid() {

		TradingServiceResp placeOrderResp = payOrder();

		OrderPo orderPo = placeOrderResp.getOrderList().get(0).getOrderPo();

		long orderId = orderPo.getOrderId();
		long userId = placeOrderResp.getUserId();

		cancelOrder(orderId, CancelOrderTypeEnum.BUYER_CANCEL_ORDER, userId);

		return placeOrderResp;

	}

	/**
	 * 创建一个用余额支付成的订单
	 * 
	 * @return
	 */
	public static TradingServiceResp payOrder() {

		TradingServiceResp placeOrderResp = TradingPlaceOrderCallService
				.placeOrderWithTwoProcutInOneOrder(false, false);

		try {
			String acc = AccountCallServiceV2.getAccountId(Long.valueOf(
					placeOrderResp.getUserId()).intValue());
			AccountCallServiceV2.resetAccount(acc, new BigDecimal("10000"),
					new BigDecimal("0"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		payOrder(placeOrderResp.getUserId(), placeOrderResp.getPayableAmount(),
				placeOrderResp.getMainOrderId(), "13");

		return placeOrderResp;

	}

	/**
	 * 创建一个用余额支付成的订单
	 * 
	 * @userId
	 * @return
	 */
	public static TradingServiceResp payOrder(int userId) {

		TradingServiceResp placeOrderResp = TradingPlaceOrderCallService
				.placeOrderWithUserId(userId);
		try {
			String acc = AccountCallServiceV2.getAccountId(Long.valueOf(
					placeOrderResp.getUserId()).intValue());
			AccountCallServiceV2.resetAccount(acc, new BigDecimal("10000"),
					new BigDecimal("0"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		payOrder(placeOrderResp.getUserId(), placeOrderResp.getPayableAmount(),
				placeOrderResp.getMainOrderId(), "13");

		return placeOrderResp;

	}

	/**
	 * 创建一个买手已接单的订单
	 * 
	 * @return
	 */
	public static TradingServiceResp orderAccept() {

		TradingServiceResp placeOrderResp = payOrder();

		OrderPo orderPo = placeOrderResp.getOrderList().get(0).getOrderPo();

		long orderId = orderPo.getOrderId();

		// TODO 老交易下线后 去掉
		TradingSyncService.riskControlNotify(orderId, "pass");

		sellerAcceptOrder(orderPo.getSellerId(), orderId);

		return placeOrderResp;

	}

	/**
	 * 订单付款（预付款）时，应付的现金金额
	 * 
	 * @param traingid
	 * @return
	 */
	public static BigDecimal getPayableAmount(long traingid) {

		List<OrderPo> res = new OrderShardingWapper()
				.selectOrderbyMainOrderId(traingid);

		BigDecimal total = BigDecimal.ZERO;
		for (OrderPo orderPo : res) {
			total = total.add(getPayableAmount(orderPo));
		}

		return total;
	}

	/**
	 * 订单付款（预付款）时，应付的现金金额
	 * 
	 * @param orderId
	 * @return
	 */
	private static BigDecimal getPayableAmount(OrderPo orderPo) {

		return orderPo
				.getTotalPrice()
				.add(orderPo.getFreight())
				.add(orderPo.getOrderDiscount())
				.subtract(
						orderPo.getYmtCouponAmount().add(
								orderPo.getSellerCouponAmount()))
				.subtract(orderPo.getPromotionAmount())
				.subtract(orderPo.getYmtPromotionAmount());
	}

	/**
	 * 支付订单
	 * 
	 * @param userId
	 * @param useAccountAmount
	 * @param tradingId
	 */
	public static Long payOrder(long userId, BigDecimal useAccountAmount,
			long tradingId) {

		return payOrder(userId, useAccountAmount, tradingId, false, 1);
	}

	/**
	 * 支付订单
	 * 
	 * @param userId
	 * @param useAccountAmount
	 * @param tradingId
	 * @param payType
	 */
	public static Long payOrder(long userId, BigDecimal useAccountAmount,
			long tradingId, int tradeType) {

		return payOrder(userId, useAccountAmount, tradingId, false, tradeType);
	}

	/**
	 * 支付订单
	 * 
	 * @param userId
	 * @param useAccountAmount
	 * @param tradingId
	 * @param canPayDeductAmount
	 */
	public static Long payOrder(long userId, BigDecimal useAccountAmount,
			long tradingId, boolean canPayDeductAmount) {

		return payOrder(userId, useAccountAmount, tradingId,
				canPayDeductAmount, 1);
	}

	/**
	 * 支付订单
	 * 
	 * @param userId
	 * @param useAccountAmount
	 * @param tradingId
	 * @param thirdPartyDiscountAmount
	 */
	public static Long payOrder(long userId, BigDecimal useAccountAmount,
			long tradingId, BigDecimal totalPrice,
			BigDecimal thirdPartyDiscountAmount) {

		return payOrder(userId, useAccountAmount, tradingId, false, totalPrice,
				thirdPartyDiscountAmount);
	}

	/**
	 * 支付订单
	 * 
	 * @param userId
	 * @param useAccountAmount
	 * @param tradingId
	 * @param canPayDeductAmount
	 * @param thirdPartyDiscountAmount
	 * @throws Exception
	 */
	public static Long payOrder(Long userId, BigDecimal useAccountAmount,
			long tradingId, boolean canPayDeductAmount, BigDecimal totalPrice,
			BigDecimal thirdPartyDiscountAmount) {

		PayReq payReq = new PayReq();

		PayReqCall payReqCall = new PayReqCall();

		long thirdTradingId = 0;

		// 参数
		payReq.setUserId(userId);
		payReq.setCallbackUrl("www.ymatou.com");
		payReq.setUseAccountAmount(useAccountAmount);
		payReq.setTradingId(tradingId);
		String tradingPassword = "abc123";
		payReq.setTradingPwd(tradingPassword);
		payReq.setUserIp("127.0.0.10");

		payReq.setTerminalSource(TerminalSourceEnum.IOS);

		payReq.setPayType("15");
		payReq.setCanPayDeduct(canPayDeductAmount);

		payReqCall.setData(false, payReq);

		try {

			Logger.comment(String.format("用户  %s , 订单支付,交易号 %s, 付款账户余额 : %s ",
					userId, tradingId, useAccountAmount));

			payReqCall.callService();

			thirdTradingId = payReqCall.getData().getLong("tradingId");

		} catch (Exception e) {
			Logger.info(String.format("########支付订单 交易号:%s 异常", tradingId));
		}

		// 支付网关支付回调交易
		try {
			PayGateWayCallService.notifyCall("15",
					String.valueOf(thirdTradingId),
					totalPrice.subtract(useAccountAmount).toString(),
					userId.intValue(), thirdPartyDiscountAmount);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return thirdTradingId;
	}

	/**
	 * 支付订单
	 * 
	 * @param userId
	 * @param useAccountAmount
	 * @param tradingId
	 * @param canPayDeductAmount
	 */
	public static Long payOrder(long userId, BigDecimal useAccountAmount,
			long tradingId, boolean canPayDeductAmount, int tradeType) {

		PayReq payReq = new PayReq();

		PayReqCall payReqCall = new PayReqCall();

		long thirdTradingId = 0;

		// 参数
		payReq.setUserId(userId);
		payReq.setCallbackUrl("www.ymatou.com");
		payReq.setUseAccountAmount(useAccountAmount);
		payReq.setTradingId(tradingId);
		String tradingPassword = userId == 30164301 ? "Abc123456" : "abc123";
		// String tradingPassword = "123456";
		payReq.setTradingPwd(tradingPassword);
		payReq.setUserIp("127.0.0.10");
		payReq.setTradeType(tradeType);

		payReq.setTerminalSource(TerminalSourceEnum.IOS);

		payReq.setPayType("13");
		payReq.setCanPayDeduct(canPayDeductAmount);

		payReqCall.setData(false, payReq);

		try {

			Logger.comment(String.format("用户  %s , 订单支付,交易号 %s, 付款账户余额 : %s ",
					userId, tradingId, useAccountAmount));

			payReqCall.callService();

			thirdTradingId = payReqCall.getData().getLong("tradingId");

			if (payReqCall.getData().optString("errorMessage")
					.equalsIgnoreCase("账户金额不足")) {

				String accountid1 = AccountCallServiceV2
						.getAccountId((int) userId);
				AccountCallServiceV2.resetAccount(accountid1, new BigDecimal(
						9000000), new BigDecimal(0));

				payOrder(userId, useAccountAmount, tradingId,
						canPayDeductAmount, tradeType);
			}
		} catch (Exception e) {
			Logger.info(e.toString());
			Logger.info(String.format("########支付订单 交易号:%s 异常", tradingId));
		}

		return thirdTradingId;
	}

	public static Long payOrder(long userId, BigDecimal useAccountAmount,
			long tradingId, String payType) {
		return payOrder(userId, useAccountAmount, tradingId, payType, 1);
	}

	/**
	 * 支付订单
	 * 
	 * @param userId
	 * @param useAccountAmount
	 * @param tradingId
	 * @param payType
	 */
	public static Long payOrder(long userId, BigDecimal useAccountAmount,
			long tradingId, String payType, int tradeType) {

		PayReq payReq = new PayReq();

		PayReqCall payReqCall = new PayReqCall();

		long thirdTradingId = 0;

		// 参数
		payReq.setUserId(userId);
		payReq.setCallbackUrl("www.ymatou.com");
		payReq.setUseAccountAmount(useAccountAmount);
		payReq.setTradingId(tradingId);
		String tradingPassword = "abc123";
		payReq.setTradingPwd(tradingPassword);
		payReq.setUserIp("127.0.0.10");
		payReq.setBankId("");
		payReq.setTradeType(tradeType);

		payReq.setTerminalSource(TerminalSourceEnum.IOS);

		if (payType.equals("70")) {

			payType = "13";

			// 转宝付 70 支付渠道
			payReq.setOptionalPayTypes(Arrays.asList(70));
		}

		payReq.setPayType(payType);
		payReqCall.setData(false, payReq);

		try {

			Logger.comment(String.format("用户  %s , 订单支付,交易号 %s, 付款账户余额 : %s ",
					userId, tradingId, useAccountAmount));

			if (useAccountAmount.compareTo(BigDecimal.ZERO) == 0) {

				String accountid1;
				try {
					accountid1 = AccountCallServiceV2
							.getAccountId((int) userId);
					AccountCallServiceV2.resetAccount(accountid1,
							new BigDecimal(9000000), new BigDecimal(0));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			payReqCall.callService();

			thirdTradingId = payReqCall.getData().getLong("tradingId");

			// TODO 老交易下线后 去掉
			Thread.sleep(2000);

		} catch (Exception e) {
			Logger.info(String.format("########支付订单 交易号:%s 异常", tradingId));
		}

		return thirdTradingId;
	}

	/**
	 * 商家接单
	 * 
	 * @param sellerId
	 * @param orderId
	 */
	public static void sellerAcceptOrder(long sellerId, long orderId) {

		// TODO 老交易下线后 去掉
		TradingSyncService.riskControlNotify(orderId, "pass");

		AcceptOrderReq acceptorderbean = new AcceptOrderReq();

		SellerAcceptOrderCall acceptordercall = new SellerAcceptOrderCall();

		// 接单
		acceptorderbean.setOrderId(orderId);
		acceptorderbean.setSellerId(sellerId);
		acceptorderbean.setCsId(1234);

		// 发送请求
		acceptordercall.setData(false, acceptorderbean);
		try {

			Logger.comment(String.format("orderId %s, sellerId %s 接单 , ",
					orderId, sellerId));

			acceptordercall.callService();
		} catch (Exception e) {
			Logger.info(String.format("########商家接单  订单号:%s 异常", orderId));
		}

	}

	/**
	 * 创建一个申请退款中的订单
	 * 
	 * @return
	 */
	public static TradingServiceResp orderApplyRefund() {
		TradingServiceResp resp = orderAccept();

		RefundService.applyRefund(resp.getOrderList().get(0));

		return resp;
	}

	/**
	 * 创建一个 已发货订单
	 * 
	 * @return
	 */
	public static TradingServiceResp orderDelivery() {
		TradingServiceResp resp = orderAccept();

		Order order = resp.getOrderList().get(0);

		long sellerId = order.getSellerId();
		long orderId = order.getOrderId();

		delivery(sellerId, orderId, true);

		return resp;
	}

	/**
	 * 码头保存发货物流单号
	 * 
	 * @param orderId
	 * @param sellerId
	 * @param billCode
	 */
	public static void saveDeliverSummary(long orderId, long sellerId,
			String billCode) {

		try {
			YmatouEasyCall SaveDeliverSummaryCall = new YmatouEasyCall("",
					"POST", "JSON");
			StringBuffer saveDeliverSummaryString = new StringBuffer();
			saveDeliverSummaryString
					.append("{\"SaveDeliverSummaryInfos\":[{\"BillCode\":\"");
			saveDeliverSummaryString.append(billCode);
			saveDeliverSummaryString.append("\",");
			saveDeliverSummaryString
					.append("\"CanReDelivery\":0,\"CatalogStatus\":\"7\",\"DeliverType\":2,\"ExpressCode\":\"xlobo\",\"InnerExpressCode\":\"\",\"IsChinaDeliver\":true,");
			saveDeliverSummaryString.append("\"OrderId\":");
			saveDeliverSummaryString.append(orderId);
			saveDeliverSummaryString.append(",");
			saveDeliverSummaryString
					.append("\"Provider\":\"洋码头官方合作物流（xLobo贝海国际速递）\",");
			saveDeliverSummaryString.append("\"SellerId\":");
			saveDeliverSummaryString.append(sellerId);
			saveDeliverSummaryString.append(",");
			saveDeliverSummaryString.append("\"Weight\":10}]}");
			SaveDeliverSummaryCall
			// .setUrl("http://orderdelivery.iapi.ymatou.com/api/Deliver/SaveDeliverSummary");
					.setUrl("http://api.seller.ymatou.com/api/Deliver/SaveDeliverSummary");

			SaveDeliverSummaryCall.setData(saveDeliverSummaryString.toString());

			Logger.comment("发货保存运单号");
			SaveDeliverSummaryCall.callService();

		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * 订单发货
	 * 
	 * @param sellerId
	 * @param orderId
	 * @param isShippedByXlobo
	 * @return 物流单号
	 */
	public static String delivery(Long sellerId, long orderId,
			boolean isShippedByXlobo) {

		DeliverGoodsReq deliveryReq = new DeliverGoodsReq();
		DeliverGoodsCall deliveryCall = new DeliverGoodsCall();

		// 物流单号
		String DeliverSummary = TestDataManager.randomStr(13);

		DeliveryInfo deliveryInfo = new DeliveryInfo();

		deliveryInfo.setBillNo(DeliverSummary);
		deliveryInfo.setYmtExpressCode("Y013");
		deliveryInfo.setExpressName("ems");
		deliveryInfo.setDeliverySection(3);
		deliveryInfo.setDeliverySource(1);
		deliveryInfo.setOrderId(orderId);

		deliveryReq.setSellerId(sellerId);
		deliveryReq.setDeliveryInfos(Arrays.asList(deliveryInfo));

		deliveryCall.setData(false, deliveryReq);

		try {
			deliveryCall.callService();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return DeliverSummary;
	}

	/**
	 * 订单发货
	 * 
	 * @param sellerId
	 * @param orderId
	 * @param LogisticsType
	 *            :Unknown(0),China(1),US(2),SailProtect(3),BondedDelivery(4),
	 *            XloboBondedDelivery
	 *            (5),AuthenticatedDirectDelivery(6),PackageDelivery
	 *            (7),AutoDelivery(8)
	 * @param section
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String delivery(Long sellerId, long orderId,
			LogisticsTypeEnum logisticsType, int section)
			throws ClientProtocolException, IOException {

		DeliverGoodsReq deliveryReq = new DeliverGoodsReq();
		DeliverGoodsCall deliveryCall = new DeliverGoodsCall();
		DeliveryInfo dInfo = new DeliveryInfo();
		String billNo = TestDataManager.getRandomNum(13);

		deliveryReq.setSellerId(sellerId);

		dInfo.setDeliverySection(section);
		dInfo.setDeliverySource(1);
		dInfo.setExpressName("sf");
		dInfo.setBillNo(billNo);
		dInfo.setYmtExpressCode("Y013");
		dInfo.setOrderId(orderId);

		deliveryReq.setDeliveryInfos(Lists.newArrayList(dInfo));

		deliveryCall.setData(deliveryReq);
		deliveryCall.callService();

		return billNo;
	}

	/**
	 * 订单发货
	 * 
	 * @param sellerId
	 * @param orderId
	 * @param LogisticsType
	 *            :Unknown(0),China(1),US(2),SailProtect(3),BondedDelivery(4),
	 *            XloboBondedDelivery
	 *            (5),AuthenticatedDirectDelivery(6),PackageDelivery
	 *            (7),AutoDelivery(8)
	 * @param section
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String delivery(Long sellerId, long orderId,
			LogisticsTypeEnum logisticsType, String ymtExpressCode, int section)
			throws ClientProtocolException, IOException {

		return delivery(sellerId, orderId, logisticsType, ymtExpressCode,
				section, null);
	}

	/**
	 * 
	 * @param sellerId
	 * @param orderId
	 * @param logisticsType
	 * @param ymtExpressCode
	 * @param section
	 * @param authenticatePackage
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String delivery(Long sellerId, long orderId,
			LogisticsTypeEnum logisticsType, String ymtExpressCode,
			int section, Boolean authenticatePackage)
			throws ClientProtocolException, IOException {

		DeliverGoodsReq deliveryReq = new DeliverGoodsReq();
		DeliverGoodsCall deliveryCall = new DeliverGoodsCall();
		DeliveryInfo dInfo = new DeliveryInfo();
		String billNo = "";

		if (ymtExpressCode.equalsIgnoreCase("Y073")
				|| ymtExpressCode.equalsIgnoreCase("Y047")
				|| ymtExpressCode.equalsIgnoreCase("Y136")) {

			billNo = TestDataManager.getRandomNum(12);
			dInfo.setMobile("13612345678");
		} else if (ymtExpressCode.equalsIgnoreCase("Y068")) {
			billNo = "DB2533011979US";
		} else {

			billNo = TestDataManager.getRandomNum(13);
		}

		dInfo.setBillNo(billNo);

		// 发货节点、1国际段,2转运段,3国内段
		dInfo.setDeliverySection(section);
		dInfo.setDeliverySource(1);
		dInfo.setExpressName("sf");
		dInfo.setYmtExpressCode(ymtExpressCode);
		dInfo.setOrderId(orderId);
		dInfo.setAuthenticatePackage(authenticatePackage);

		deliveryReq.setDeliveryInfos(Lists.newArrayList(dInfo));
		deliveryReq.setSellerId(sellerId);

		deliveryCall.setData(deliveryReq);
		deliveryCall.callService();

		return billNo;
	}

	/**
	 * 鉴定中心发货
	 * 
	 * @param sellerId
	 * @param orderId
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String authenticateDelivery(Long sellerId, long orderId)
			throws ClientProtocolException, IOException {

		AuthenticateDeliveryReq authenticateDeliveryReq = new AuthenticateDeliveryReq();
		AuthenticateDeliveryCall authenticateDeliveryCall = new AuthenticateDeliveryCall();

		String billNo = TestDataManager.getRandomNum(13);

		authenticateDeliveryReq.setSellerId(sellerId);
		authenticateDeliveryReq.setOrderId(orderId);
		authenticateDeliveryReq.setBillNo(billNo);
		authenticateDeliveryReq.setExpressCompany("鉴定中心发货");
		authenticateDeliveryReq.setYmtExpressCode("Y013");

		authenticateDeliveryCall.setData(authenticateDeliveryReq);
		authenticateDeliveryCall.callService();

		return billNo;
	}

	/**
	 * 创建一个确认收货订单
	 * 
	 * @return
	 */
	public static TradingServiceResp orderConfirmReceive() {
		TradingServiceResp resp = orderDelivery();

		long orderId = resp.getOrderList().get(0).getOrderId();

		confirmReceive(resp.getUserId(), orderId);

		return resp;
	}

	/**
	 * 订单确认收货
	 * 
	 * @param userId
	 * @param orderId
	 */
	public static void confirmReceive(long userId, long orderId) {

		ConfirmReceiveReq confirmReceiveReq = new ConfirmReceiveReq();
		ConfirmReceiveCall confirmreceivecall = new ConfirmReceiveCall();

		// 确认收货请求
		confirmReceiveReq.setBuyerId(userId);
		confirmReceiveReq.setOrderId(orderId);
		confirmReceiveReq.setRemark("收到了啊");
		confirmReceiveReq.setIgnoreXloboSignedCheck(true);
		// 发送请求
		confirmreceivecall.setData(false, confirmReceiveReq);
		try {
			confirmreceivecall.callService();
		} catch (Exception e) {

			e.printStackTrace();
		}

	}

	/**
	 * 锁定，解锁订单
	 * 
	 * @param orderId
	 * @param islock
	 *            1 锁定 , 非1 解锁
	 */
	public static void markOrderLock(long orderId, int islock) {

		MarkOrderLockReq markOrderLockReq = new MarkOrderLockReq();
		MarkOrderLockCall markOrderLockCall = new MarkOrderLockCall();

		// 参数
		markOrderLockReq.setOrderId(orderId);
		markOrderLockReq.setLockStatus(islock);

		// 发送请求
		markOrderLockCall.setData(false, markOrderLockReq);

		try {
			markOrderLockCall.callService();
		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	/**
	 * 生成结算
	 * 
	 * @param orderId
	 * @param buyerId
	 * @param sellerId
	 * @param totalPrice
	 */
	public static void generateInvoicesOnOrderReceived(long orderId,
			long buyerId, BigDecimal totalPrice, long sellerId) {

		try {

			for (int i = 0; i < 5; i++) {

				Thread.sleep(i * 1000 + 5000);

				YmatouEasyCall generateInvoicesCall = new YmatouEasyCall("",
						"POST", "JSON");
				StringBuffer generateInvoicesString = new StringBuffer();
				generateInvoicesString.append("{\"BuyerId\":");
				generateInvoicesString.append(buyerId);
				generateInvoicesString.append(",");
				generateInvoicesString
						.append("\"appId\":\"optrade.iapi.ymatou.com\",\"BusinessType\":4,\"ParamExt\":{\"IsShippedByXlobo\":\"false\",");
				generateInvoicesString.append("\"TotalPrice\":");
				generateInvoicesString.append(totalPrice);
				generateInvoicesString.append(",");
				generateInvoicesString.append("\"BizCode\":\"100102\"},");
				generateInvoicesString.append("\"OrderId\":");
				generateInvoicesString.append(orderId);
				generateInvoicesString.append(",");

				generateInvoicesString.append("\"SellerId\":");
				generateInvoicesString.append(sellerId);
				generateInvoicesString.append("}");
				generateInvoicesCall
						.setUrl("http://settlement.iapi.ymatou.com/api/generateInvoicesOnOrderReceived");

				generateInvoicesCall.setData(generateInvoicesString.toString());

				Logger.comment("生成结算");
				generateInvoicesCall.callService();

				if ("ok".equalsIgnoreCase(generateInvoicesCall.getReturnData()))
					break;
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	/**
	 * 获取买手的保密协议签约状态
	 * 
	 * @param sellerId
	 */
	public static boolean checkSignedBAOMI(long sellerId) {

		try {
			YmatouEasyCall checkSignedBAOMICall = new YmatouEasyCall("",
					"POST", "JSON");
			StringBuffer checkSignedBAOMIString = new StringBuffer();
			checkSignedBAOMIString.append("{\"sellerIDs\":[");
			checkSignedBAOMIString.append(sellerId);
			checkSignedBAOMIString.append("]}");

			checkSignedBAOMICall
					.setUrl("http://sellerquery.iapi.ymatou.com/api/CheckSignedBAOMI");

			checkSignedBAOMICall.setData(checkSignedBAOMIString.toString());

			Logger.comment("获取买手的保密协议签约状态");
			checkSignedBAOMICall.callService();

			return new JSONObject(checkSignedBAOMICall.getReturnData())
					.optJSONObject("Data").optJSONObject("Protocols")
					.optBoolean(String.valueOf(sellerId));

		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
	}

	/**
	 * 检查买手是否在拼邮溯源白名单中(true-在，false-不在)
	 * 
	 * @param sellerId
	 */
	public static boolean checkSwitchBySellerId(long sellerId) {

		try {
			YmatouEasyCall checkSwitchBySellerIdCall = new YmatouEasyCall("",
					"POST", "JSON");
			StringBuffer checkSwitchBySellerIdCallString = new StringBuffer();
			checkSwitchBySellerIdCallString.append("{\"SellerId\":");
			checkSwitchBySellerIdCallString.append(sellerId);
			checkSwitchBySellerIdCallString
					.append(", \"SpecialBusinessNo\":\"pysy0001\"}");

			checkSwitchBySellerIdCall
					.setUrl("http://sellerAllocation.iapi.ymatou.com/api/SpecialService/CheckSwitch");

			checkSwitchBySellerIdCall.setData(checkSwitchBySellerIdCallString
					.toString());

			Logger.comment("检查买手是否在拼邮溯源白名单中");
			checkSwitchBySellerIdCall.callService();

			return new JSONObject(checkSwitchBySellerIdCall.getReturnData())
					.optJSONObject("Data").optBoolean("IsEnable");

		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
	}

	/**
	 * 商品支付金额（不包含运费）
	 * 
	 * @param orderDetailPo
	 * @return
	 */
	public static BigDecimal getOrderDetailPaidAmountExcludeFreight(
			OrderDetailPo orderDetailPo) {
		return Utils
				.zeroIfNull(orderDetailPo.getProductPrice())
				.multiply(new BigDecimal(orderDetailPo.getProductCount()))
				.add(Utils.zeroIfNull(orderDetailPo.getDiscount()))
				.subtract(Utils.zeroIfNull(orderDetailPo.getYmtCouponAmount()))
				.subtract(
						Utils.zeroIfNull(orderDetailPo.getSellerCouponAmount()))
				.subtract(Utils.zeroIfNull(orderDetailPo.getPromotionAmount()))
				.subtract(
						Utils.zeroIfNull(orderDetailPo.getYmtPromotionAmount()))
				.subtract(Utils.zeroIfNull(orderDetailPo.getRebatePaidAmount()))
				.subtract(
						Utils.zeroIfNull(orderDetailPo
								.getIntegralDeductionAmount()));
	}

	/**
	 * 商品支付金额
	 * 
	 * @param orderDetailPo
	 * @return
	 */
	public static BigDecimal getOrderDetailPaidAmount(
			OrderDetailPo orderDetailPo) {
		return Utils
				.zeroIfNull(orderDetailPo.getProductPrice())
				.multiply(new BigDecimal(orderDetailPo.getProductCount()))
				.add(Utils.zeroIfNull(orderDetailPo.getDiscount()))
				.subtract(Utils.zeroIfNull(orderDetailPo.getYmtCouponAmount()))
				.subtract(
						Utils.zeroIfNull(orderDetailPo.getSellerCouponAmount()))
				.subtract(Utils.zeroIfNull(orderDetailPo.getPromotionAmount()))
				.subtract(
						Utils.zeroIfNull(orderDetailPo.getYmtPromotionAmount()))
				.subtract(Utils.zeroIfNull(orderDetailPo.getRebatePaidAmount()))
				.subtract(
						Utils.zeroIfNull(orderDetailPo
								.getIntegralDeductionAmount()))
				.add(Utils.zeroIfNull(orderDetailPo.getFreight()));
	}

	public static Boolean isCanceledOrder(OrderPo orderPo) {

		if (orderPo.getOrderStatus() == 13 || orderPo.getOrderStatus() == 12
				|| orderPo.getOrderStatus() == 18)
			return true;
		else
			return false;
	}

	public static String queryByTradingId(String paymentId) throws Exception {

		QueryByTradingIdBean queryByTradingIdBean = new QueryByTradingIdBean();
		QueryByTradingIdCall queryByTradingIdCall = new QueryByTradingIdCall();

		queryByTradingIdBean.setTradingId(paymentId);

		queryByTradingIdCall.setData(queryByTradingIdBean);

		queryByTradingIdCall.callService();

		JSONObject object = new JSONObject(queryByTradingIdCall.getReturnData())
				.getJSONObject("Result");

		return String.valueOf(object.getDouble("OrderAmt"));
	}

	/**
	 * 保存已签收的物流信息
	 * 
	 * @param billCode
	 */
	public static void saveLogisticsInfo(String billCode) {

		try {
			YmatouEasyCall saveLogisticsInfoCall = new YmatouEasyCall("",
					"POST", "JSON");
			StringBuffer saveLogisticsInfoString = new StringBuffer();

			saveLogisticsInfoString
					.append("{\"bizContent\":\"{\\\"cpCode\\\":\\\"ZTO\\\", ");
			saveLogisticsInfoString.append("\\\"mailNo\\\":\\\"" + billCode
					+ "\\\",");
			saveLogisticsInfoString
					.append("\\\"logisticsGmtModified\\\":\\\"2020-06-17 17:03:24\\\",");
			saveLogisticsInfoString.append("\\\"bizKey\\\":\\\"" + billCode
					+ "\\\",");
			saveLogisticsInfoString
					.append("\\\"logisticsStatusDesc\\\":\\\"已签收\\\",");
			saveLogisticsInfoString
					.append("\\\"lastLogisticDetail\\\":\\\"[代收点]您的快件已签收，签收人在【丰巢的新华.天玺大厦(丰巢智能快递柜)】(新华.天玺大厦D座员工通道)领取,如有疑问请电联：4000633333, 投诉电话：13644023631, 您的快递已经妥投。风里来雨里去, 只为客官您满意。上有老下有小, 赏个好评好不好？【请在评价快递员处帮忙点亮五颗星星哦~】\\\",");
			saveLogisticsInfoString
					.append("\\\"logisticsStatus\\\":\\\"SIGN\\\"}\",");
			saveLogisticsInfoString
					.append("\"billNo\": \"" + billCode + "\", ");
			saveLogisticsInfoString.append("\"platform\":4}");

			saveLogisticsInfoCall
					.setUrl("http://recvlogistics.iapi.ymatou.com/Express/SaveLogisticsInfo");
			saveLogisticsInfoCall.setData(saveLogisticsInfoString.toString());

			Logger.comment("保存已签收的物流信息");
			saveLogisticsInfoCall.callService();

		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public static void syncSignedOrderBizParam(Long orderId, String billCode)
			throws ClientProtocolException, IOException {

		SyncSignedOrderReq syncSignedOrderReq = new SyncSignedOrderReq();
		SyncSignedOrderCall syncSignedOrderCall = new SyncSignedOrderCall();

		SyncSignedOrderBizParamVo bizParam = new SyncSignedOrderBizParamVo();

		bizParam.setOrderId(orderId);
		bizParam.setBillCode(billCode);
		bizParam.setNodeStatus(5);

		syncSignedOrderReq.setAppId("autotest");
		syncSignedOrderReq.setBizkey(String.valueOf(orderId));
		syncSignedOrderReq.setBizParam(bizParam);
		syncSignedOrderReq.setBizType("LogisticsNotify");

		syncSignedOrderCall.setData(syncSignedOrderReq);
		syncSignedOrderCall.callService();
	}

	public static void authenticateCenterNotify(Long orderId, String catalogId)
			throws ClientProtocolException, IOException {

		AuthenticateCenterNotifyReq authenticateCenterNotifyReq = new AuthenticateCenterNotifyReq();
		AuthenticateCenterNotifyCall authenticateCenterNotifyCall = new AuthenticateCenterNotifyCall();

		List<IdentifyProdArrivedVo> prodArriveds = new ArrayList<>();

		IdentifyProdArrivedVo identifyProdArrivedVo = new IdentifyProdArrivedVo();

		identifyProdArrivedVo.setCatalogId(catalogId);
		identifyProdArrivedVo.setLogisticNo("autotest_billNo");
		identifyProdArrivedVo.setArrivedNumber(1);

		prodArriveds.add(identifyProdArrivedVo);

		authenticateCenterNotifyReq.setProdArriveds(prodArriveds);
		authenticateCenterNotifyReq.setOrderId(orderId);

		authenticateCenterNotifyCall.setData(authenticateCenterNotifyReq);
		authenticateCenterNotifyCall.callService();
	}

	/**
	 * 物流消息 = 到达鉴别中心
	 * 
	 * @param orderId
	 * @param catalogId
	 * @param billNo
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static void authenticateCenterNotify(Long orderId, String catalogId,
			String billNo) throws ClientProtocolException, IOException {

		AuthenticateCenterNotifyReq authenticateCenterNotifyReq = new AuthenticateCenterNotifyReq();
		AuthenticateCenterNotifyCall authenticateCenterNotifyCall = new AuthenticateCenterNotifyCall();

		List<IdentifyProdArrivedVo> prodArriveds = new ArrayList<>();

		IdentifyProdArrivedVo identifyProdArrivedVo = new IdentifyProdArrivedVo();

		identifyProdArrivedVo.setCatalogId(catalogId);
		identifyProdArrivedVo.setLogisticNo(billNo);
		identifyProdArrivedVo.setArrivedNumber(1);

		prodArriveds.add(identifyProdArrivedVo);

		authenticateCenterNotifyReq.setProdArriveds(prodArriveds);
		authenticateCenterNotifyReq.setOrderId(orderId);

		authenticateCenterNotifyCall.setData(authenticateCenterNotifyReq);
		authenticateCenterNotifyCall.callService();
	}

	/**
	 * 修改/补录运单号
	 * 
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String modifyOrSupplementBillNo(long orderId, long sellerId,
			String ymtExpressCode, Integer section)
			throws ClientProtocolException, IOException {

		ModifyOrSupplementBillNoReq modifyOrSupplementBillNoReq = new ModifyOrSupplementBillNoReq();
		ModifyOrSupplementBillNoCall modifyOrSupplementBillNoCall = new ModifyOrSupplementBillNoCall();

		ModifyOrSupplementBillNoInfo dInfo = new ModifyOrSupplementBillNoInfo();

		dInfo.setBillNo(TestDataManager.getRandomNum(13));
		dInfo.setSource(13);

		// 发货节点、1国际段,2转运段,3国内段
		dInfo.setDeliverySection(section);
		dInfo.setYmtExpressCode(ymtExpressCode);

		modifyOrSupplementBillNoReq
				.setBillNoInfoList(Lists.newArrayList(dInfo));
		modifyOrSupplementBillNoReq.setOrderId(orderId);
		modifyOrSupplementBillNoReq.setSellerId(sellerId);

		modifyOrSupplementBillNoCall.setData(modifyOrSupplementBillNoReq);
		modifyOrSupplementBillNoCall.callService();

		return dInfo.getBillNo();
	}

	/**
	 * 修改/补录运单号
	 * 
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String modifyOrSupplementBillNo(long orderId, long sellerId,
			String ymtExpressCode, Integer section, Boolean authenticatePackage)
			throws ClientProtocolException, IOException {

		ModifyOrSupplementBillNoReq modifyOrSupplementBillNoReq = new ModifyOrSupplementBillNoReq();
		ModifyOrSupplementBillNoCall modifyOrSupplementBillNoCall = new ModifyOrSupplementBillNoCall();

		ModifyOrSupplementBillNoInfo dInfo = new ModifyOrSupplementBillNoInfo();

		dInfo.setBillNo(TestDataManager.getRandomNum(13));
		dInfo.setSource(13);

		// 发货节点、1国际段,2转运段,3国内段
		dInfo.setDeliverySection(section);
		dInfo.setYmtExpressCode(ymtExpressCode);
		dInfo.setAuthenticatePackage(authenticatePackage);

		modifyOrSupplementBillNoReq
				.setBillNoInfoList(Lists.newArrayList(dInfo));
		modifyOrSupplementBillNoReq.setOrderId(orderId);
		modifyOrSupplementBillNoReq.setSellerId(sellerId);

		modifyOrSupplementBillNoCall.setData(modifyOrSupplementBillNoReq);
		modifyOrSupplementBillNoCall.callService();

		return dInfo.getBillNo();
	}

	public static void main(String... args) throws Exception {

		// System.out.println(TradingCallService.queryByTradingId("13801998699"));

		/*
		 * AddSellerProductRequest addSellerProductBean =
		 * ProductManagerCallServiceV2
		 * .initAddSellerGlobalPspProductRequest(20336378);
		 * 
		 * String productId = ProductManagerCallServiceV2
		 * .addNewProduct(addSellerProductBean).get("Data")
		 * .getAsJsonObject().get("ProductId").getAsString(); List<YmtCatalogsI>
		 * catalogslist = new YmtCatalogsIWapper()
		 * .selectCatalogsByProductId(productId);
		 * 
		 * ProductManagerCallServiceV2.AddSellerGlobalPspProduct(20336378,
		 * productId);
		 * ProductManagerCallServiceV2.UpdateProductCommision(20336378,
		 * productId, "fyftest1", new BigDecimal(0.15));
		 * System.out.println(productId);
		 */
		/*
		 * TradingServiceResp resp = TradingCallService.placeOrder1(true,
		 * false);
		 * 
		 * int orderId = (int) resp.getOrderList().get(0).getOrderId(); int
		 * userId = (int) resp.getUserId();
		 * 
		 * orderCallService.orderPayRequest((int) resp.getUserId(),
		 * resp.getPayableAmount(), resp.getMainOrderId());
		 */

		// creaderPro(24635724L, "autotest1", 1000000);

		// orderCallService.cancelOrder(orderId, userId);
		// TradingCallService.placeHunterOrder(1234, 2);
		// PlaceOrderReq req =
		// TradingCallService.buildStandPlaceOrderReq(false);
		//
		// long sellerId = 20227567;
		//
		// String sellerName = "zhangyi_seller0002";
		//
		// req.getOrderGroups().get(0).setSellerId(sellerId);
		// req.getOrderGroups().get(0).setSellerLoginId(sellerName);
		//
		// OrderVo orderVo;
		//
		// //创建一个普通商品
		// TradingCallService.ProductVo pro = TradingCallService.creaderPro(
		// sellerId, sellerName, 100);
		//
		// orderVo = TradingCallService.createOrderVo(Lists.newArrayList(pro));
		//
		// orderVo.setLogisticsType(LogisticsTypeEnum.BondedDelivery);
		//
		// req.getOrderGroups().get(0).setOrders(Lists.newArrayList(orderVo));
		//
		// req.setBizSource(null);
		//
		// TradingCallService.callPlaceOrderService(req);
		//
		// TradingCallService.cancelOrder(1330014891,
		// CancelOrderTypeEnum.BUYER_CANCEL_ORDER, 20324891);

		// TradingCallService.getProductInfo("p3530445", 0);
		// TradingCallService.generateInvoicesOnOrderReceived(5201218699L,
		// 20238699, new BigDecimal("76.00"), 24635724);

		// TradingCallService.placeHunterGroupOrder(1234, 1, 20238699);
		// System.out.println(TradingCallService.checkSwitchBySellerId(24635724));

		// Logger.comment(AccountCallServiceV2.getAccountBalance((int)25324461,
		// 5).toPlainString());
		/*
		 * ProductManagerCallServiceV2.UpdateCatalogCommisions(20336378,
		 * "0eabd6fa-7d63-410e-8617-9eb3b2bc0cef",
		 * "acd74a21-b2e5-4049-89c1-65e3b92b6135", "fyftest1", new
		 * BigDecimal(9));
		 */

		// TradingCallService.payOrder(20238699, BigDecimal.valueOf(386),
		// 2074828699, false);
		// PlaceOrderService.payOrder(userId, type)
		// TradingCallService.creaderPro(Long.parseLong("24635724"),
		// "autotest1", 1);
		// TradingCallService.orderConfirmReceive();
		// TradingCallService.sellerAcceptOrder(20227567, 1120856434);;
		// resp.getOrderList();
	}
}
